import { isRef } from 'vue'

const formatRef = ref => (isRef(ref) ? ref.value : ref)

const endsWith = (target, match) => {
  let position = target.length
  position = position - match.length
  const lastIndex = target.lastIndexOf(match)
  return lastIndex !== -1 && lastIndex === position
}

const copyText = async val => {
  if (navigator.clipboard && navigator.permissions) {
    await navigator.clipboard.writeText(val)
  } else {
    const textArea = document.createElement('textArea')
    textArea.value = val
    textArea.style.width = 0
    textArea.style.position = 'fixed'
    textArea.style.left = '-999px'
    textArea.style.top = '10px'
    textArea.setAttribute('readonly', 'readonly')
    document.body.appendChild(textArea)

    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    return true
  }
}

const trimQuote = target => {
  const reg = /,$/gi
  return target.replace(reg, '')
}

const executeTransform = async (properties, typeTitle, description) => {
  try {
    if (!properties) return

    properties = formatRef(properties)
    typeTitle = formatRef(typeTitle)
    description = formatRef(description)

    properties = trimQuote(properties)

    const obj = JSON.parse('{' + properties + '}')
    const key = Reflect.ownKeys(obj)[0]
    const target = obj[key]

    typeTitle = target.title ?? typeTitle
    description = target.title ?? description
    properties = target.properties ?? JSON.parse('{' + properties + '}')

    let title = typeTitle || 'obj'
    if (endsWith(title, '对象')) {
      title = title.substring(0, title.length - 2) + 'VO'
    }
    let isQO = false
    if (endsWith(title, 'QO')) {
      isQO = true
    }

    let tempStr = ''

    tempStr += `export interface ${title} {\n`

    let keys = Object.keys(properties)
    if (isQO) {
      const qoIngoreKeys = [
        'createDept',
        'createUser',
        'createTime',
        'isDeleted',
        'status',
        'updateUser',
        'updateTime'
      ]
      keys = keys.filter(key => !qoIngoreKeys.includes(key))
    }

    // 处理id结尾的字段
    const keys2 = []
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i]
      keys2.push(key)
      if (endsWith(key, 'Id')) {
        keys2.push(`_${key}`)
      }
    }
    keys = keys2

    for (let i = 0; i < keys.length; i++) {
      const key = keys[i]
      let info = undefined
      if (key.startsWith('_')) {
        info = properties[key.substring(1)]
      } else {
        info = properties[key]
      }
      tempStr += `  /** ${info.description} */\n`
      let type = 'string'
      if (key.startsWith('_')) {
        type = 'string'
      }
      if (key === 'id') {
        type = 'string'
      } else if (key === 'createDept') {
        type = 'string'
      } else if (key === 'createUser') {
        type = 'string'
      } else if (key === 'isDeleted') {
        type = 'string'
      } else if (key === 'status') {
        type = 'string'
      } else if (key === 'updateUser') {
        type = 'string'
      } else if (endsWith(key, 'Id')) {
        type = 'string'
      } else if (info.type === 'integer') {
        type = 'number'
      }
      tempStr += '  ' + key
      if (isQO) {
        tempStr += '?'
      }
      tempStr += ': ' + type + ';\n'
    }
    tempStr += '}'

    await copyText(tempStr)
  } catch (error) {
    throw Error(error)
  }
}

export default executeTransform
